package com.suyl.easypoi.easypoidemo.excelInport.controller;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import cn.afterturn.easypoi.handler.inter.IExcelDataHandler;
import com.alibaba.fastjson.JSON;
import com.suyl.easypoi.easypoidemo.excelInport.entity.User;
import com.suyl.easypoi.easypoidemo.excelInport.handler.UserDictExcelHandler;
import com.suyl.easypoi.easypoidemo.excelInport.handler.UserExcelHandler;
import com.suyl.easypoi.easypoidemo.excelInport.handler.UserIExcelVerifyHandler;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.Map;

@RestController
public class UserExcelImportController {

    private static final Logger log = LoggerFactory.getLogger(UserExcelImportController.class);

    @PostMapping("excelImport.do")
    public void excelImport(@RequestParam("file") MultipartFile file) {
        ImportParams importParams = new ImportParams();
        // 数据处理
        IExcelDataHandler<User> handler = new UserExcelHandler();
        handler.setNeedHandlerFields(new String[]{"年龄", "姓名"});// 注意这里对应的是excel的列名。也就是对象上指定的列名。
        importParams.setDataHandler(handler);
        importParams.setDictHandler(new UserDictExcelHandler());
        importParams.setVerifyHandler(new UserIExcelVerifyHandler());
//        importParams.setI18nHandler();

        // 需要验证
        importParams.setNeedVerify(true);

        try {
            ExcelImportResult<User> result = ExcelImportUtil.importExcelMore(file.getInputStream(), User.class,
                    importParams);

            List<User> successList = result.getList();
            List<User> failList = result.getFailList();
            Map<String, Object> map = result.getMap();
            Workbook failWorkbook = result.getFailWorkbook();

            failWorkbook.getFirstVisibleTab();

            log.info("map:" + JSON.toJSON(map));
            log.info("是否存在验证未通过的数据:" + result.isVerifyFail());
            log.info("验证通过的数量:" + successList.size());
            log.info("验证未通过的数量:" + failList.size());

            for (User user : successList) {
                log.info("[成功列表信息]" + JSON.toJSON(user));
            }
            for (User user : failList) {
                log.info("【失败列表信息】" + JSON.toJSON(user));
            }
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
}
